#include "head_s.h"

int download(const user_t* status, const portocol_t* portocol, int net_fd)
{
    char file_name[60] = {0};
    char file_path[128] = {0};
    sprintf(file_name, "%s", status->arg);
    sprintf(file_path, "%s%s%s%s", status->base_path, 
                                    status->user_name, 
                                    status->path,
                                    file_name);
    //printf("gets: %s\n", file_name);
    //printf("gets: %s\n", file_path);
    int file_fd = open(file_path, O_RDWR);
    printf("file_fd = %d\n", file_fd);
    send(net_fd, &file_fd, sizeof(file_fd), MSG_NOSIGNAL);
    if (file_fd == -1)
    {
        return -1;
    }

    int file_name_len = strlen(file_name);
    send(net_fd, &file_name_len, sizeof(int), MSG_NOSIGNAL);
    send(net_fd, file_name, file_name_len, MSG_NOSIGNAL);
    
    struct stat st;
    fstat(file_fd, &st);
    size_t file_size = st.st_size;
    send(net_fd, &file_size, sizeof(size_t), MSG_NOSIGNAL);
    //int is_exist = 0;
    //recv(net_fd, &is_exist, sizeof(int), MSG_WAITALL);
    //说明文件为断点续传
   /* if (is_exist == -1)
    {
        off_t curr_size = 0;
        recv(net_fd, &curr_size, sizeof(off_t), MSG_WAITALL);
        printf("curr_size = %ld\n", curr_size);
        struct stat st;
        fstat(file_fd, &st);
        off_t need_size = st.st_size - curr_size;
        printf("need_size = %ld\n", need_size);
        send(net_fd, &need_size, sizeof(off_t), MSG_NOSIGNAL);
        sendfile(net_fd, file_fd, &curr_size, need_size);
        return 0;
    }*/
    sendfile(net_fd, file_fd, 0, file_size);
    //printf("%d\n", send_size);

    return 0;
}

